#include "connectform.h"
#include "ui_connectform.h"
#include "liwishell.h"
#include"data.h"
#include<QDebug>
#include<QList>
#include<QTime>
#include<QtSerialPort/QSerialPortInfo>
ConnectForm::ConnectForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ConnectForm)
{
    ui->setupUi(this);
   // ui->comboBox_IP->setMouseTracking(true);
  //  this->setMouseTracking(true);
    ui->radioButton_ip->setChecked(true);

    for(int i=0;i<6;++i){
        QPushButton *button=this->findChild<QPushButton*>(QString("btnEnable%1").arg(i));
        connect(button,&QPushButton::clicked,this,[=](){
            if(Data::handle!=NULL){
                if(button->text()==QString("开使能_AXIS%1").arg(i)){
                    PMC_SetAxisEnable(Data::handle,i,1);
                    button->setText(QString("关使能_AXIS%1").arg(i));
                    button->setStyleSheet("background-color: rgb(175,255,255)");
                }
                else{
                    PMC_SetAxisEnable(Data::handle,i,0);
                    button->setText(QString("开使能_AXIS%1").arg(i));
                    button->setStyleSheet("background-color: rgb(255,255,255)");
                }
            }
        });

    }


}

ConnectForm::~ConnectForm()
{
    if(Data::CardIsConnect())
        PMC_Close(Data::handle);
    delete ui;
}



void ConnectForm::on_comboBox_IP_clicked()
{
    QByteArray ipList(512,' ');
    PMC_SearchEthlist(ipList.data(),ipList.count(),200);
    QList<QByteArray> arr=  ipList.split('\0');
    ui->comboBox_IP->clear();

    for (QList<QByteArray>::Iterator var = arr.begin(); var < arr.end(); ++var) {
            ui->comboBox_IP->addItem(var.i->t());
    }
}


void ConnectForm::on_comboBox_Com_clicked()
{
    ui->comboBox_Com->clear();
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        ui->comboBox_Com->addItem(info.portName());
    }
}


void ConnectForm::on_pushButton_connect_clicked()
{
    if(Data::CardIsConnect()){
        PMC_Close(Data::handle);
        ui->pushButton_connect->setText(tr("连接"));
        Data::handle=nullptr;
        for(int i=0;i<6;++i){
            PMC_SetAxisEnable(Data::handle,i,0);
        }
    }else{
        int ret=0;
        if(ui->radioButton_ip->isChecked()){
            ret=PMC_OpenEth(ui->comboBox_IP->currentText().toStdString().c_str(),&Data::handle);
        }else if(ui->radioButton_com->isChecked()){
            ret=PMC_OpenCom(ui->spinBox_Pci->value(),&Data::handle);
        }else if(ui->radioButton_pci->isChecked()){

        }
        if(ret!=0)
            Data::handle=nullptr;
        else{
            ui->pushButton_connect->setText(tr("断开"));
            for(int i=0;i<6;++i){
                PMC_SetAxisEnable(Data::handle,i,1);
            }
        }

    }
}





